package pl.owm.readxls;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class FileReader {

	public static void main(String[] args) {

		FileReader fr = new FileReader();
		List<MonthFile> list = new ArrayList<MonthFile>();
		File root = new File("C:\\Documents and Settings\\OSP\\reporter-dane");
		List<TaskRow> tasks = fr.getTasks(root);
		System.out.print("cnt " + tasks.size());
		for (TaskRow t : tasks) {
			System.out.println(t.date.get(Calendar.DAY_OF_WEEK) + " " + t.task
					+ " proj: " + t.project + " " + t.employee + " " + t.length
					+ " minutow");
		}
	}

	private void addFiles(List<MonthFile> files, File fileOrDir) {

		if (fileOrDir != null) {
			if (fileOrDir.isDirectory()) {

				for (File file : fileOrDir.listFiles()) {
					addFiles(files, file);
				}

			} else if (fileOrDir.isFile()) {

				MonthFile monthFile = new MonthFile();
				monthFile.file = fileOrDir;
				String[] path = getLastPathSegments(monthFile.file);

				try {
					monthFile.month = Integer.parseInt(path[0]);
					monthFile.year = Integer.parseInt(path[1]);
					if (monthFile.month > 0 && monthFile.month < 13) {
						files.add(monthFile);
					} else {
						System.out
								.println("bledny miesiac: " + monthFile.month);
					}
				} catch (NumberFormatException ex) {
					System.out.println(String.format(
							"nie udalo sie dodac plikow z folderow %s/%s",
							path[1], path[0]));
				}
			}
		}
	}

	private String[] getLastPathSegments(File file) {

		String[] result = new String[2];

		File month = file.getParentFile();
		File year = month.getParentFile();

		result[0] = month.getName();
		result[1] = year.getName();
		return result;
	}

	public List<TaskRow> getTasks(File root) {

		List<MonthFile> list = new ArrayList<MonthFile>();
		List<TaskRow> task = new ArrayList<TaskRow>();
		addFiles(list, root);

		for (MonthFile monthFile : list) {
			File file = monthFile.file;
			FileInputStream fis = null;
			Workbook workBook = null;
			try {
				fis = new FileInputStream(file);
				workBook = WorkbookFactory.create(fis);
			} catch (InvalidFormatException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			String employee = file.getName();
			for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
				Sheet sheet = workBook.getSheetAt(i);
				processSheet(task, sheet, monthFile, employee);
			}

		}
		return task;
	}

	private void processSheet(List<TaskRow> tasks, Sheet currentSheet,
			MonthFile currentMonthFile, String employee) {

		String project = currentSheet.getSheetName();
		String emp = removeExtension(employee); // REMOVE
		for (int i = 1; i <= currentSheet.getLastRowNum(); i++) {

			Row row = currentSheet.getRow(i);
			TaskRow taskRow = new TaskRow();
			Cell date = row.getCell(0);
			Cell task = row.getCell(1);
			Cell length = row.getCell(2);
			if (date == null || task == null || length == null) {
				break;
			}
			taskRow.task = task.getStringCellValue();
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(date.getDateCellValue());
			taskRow.date = calendar;

			taskRow.length = (int) (length.getNumericCellValue() * 60); // TODO:
																		// improve
			taskRow.project = project;
			taskRow.employee = emp;
			// Processing
			tasks.add(taskRow);
		}
	}

	private String removeExtension(String stringFile) {

		if (stringFile.contains(".xlsx"))
			return stringFile.substring(0, stringFile.length() - 5);
		return stringFile.substring(0, stringFile.length() - 4);
	}

	public static class TaskRow {

		private String task;
		private Calendar date;

		private String project;
		private String employee;
		private int length;

		public String getTask() {
			return task;
		}

		public void setTask(String task) {
			this.task = task;
		}

		public Calendar getDate() {
			return date;
		}

		public void setDate(Calendar date) {
			this.date = date;
		}

		public String getProject() {
			return project;
		}

		public void setProject(String project) {
			this.project = project;
		}

		public String getEmployee() {
			return employee;
		}

		public void setEmployee(String employee) {
			this.employee = employee;
		}

		public int getLength() {
			return length;
		}

		public void setLength(int length) {
			this.length = length;
		}
	}

	public static class MonthFile {

		private int year;
		private File file;
		private int month;

		public int getMonth() {
			return month;
		}

		public void setMonth(int month) {
			this.month = month;
		}

		public int getYear() {
			return year;
		}

		public void setYear(int year) {
			this.year = year;
		}

		public File getFile() {
			return file;
		}

		public void setFile(File file) {
			this.file = file;
		}
	}
}
